const router = require('koa-router')()
const fs =require('fs')
router.get('/', async (ctx, next) => {
  await ctx.render('index', {
    title: 'Hello Koa 2!'
  })
})

router.get('/string', async (ctx, next) => {
  ctx.body = 'koa2 string'
})

router.get('/json', async (ctx, next) => {
  ctx.body = {
    title: 'koa2 json'
  }
})

router.post('/list2',async(ctx,next)=>{
  console.log(ctx.request.body);
  ctx.body='list2 data'
})

router.get('/list',async (ctx,next)=>{
  console.log(ctx.request.query);
  ctx.body = {
    errcode:0,
    errmsg:'ok',
    list:[
      {
        "username":"James","age":20,"gender":"男"
      },
      {
        "username":"Mary","age":20,"gender":"男"
      },
      {
        "username":"Andy","age":20,"gender":"男"
      }
    ]
  }
})

router.post('/list',async (ctx,next)=>{
  // console.log(ctx.request.body);
  var args=[
    {field:'page',type:'number'},
    {field:'count',type:'number'}
  ];
  var body = ctx.request.body;
  for(var i=0;i<args.length;i++){
    var item =args[i];
      if(!Object.keys(body).includes(item.field)){
        ctx.body={
          errcode:-1,
          errmsg:'参数个数错误'
        };
        return;
      }
      else if(typeof body[item.field]!=item.type){
          ctx.body={
            errcode:-2,
            errmsg:'参数类型错误'
          };
          return;
        }
      }

      var data = fs.readFileSync('./data/list.json');
      data = JSON.parse(data);
      var list = data.splice(body.page * body.count , body.count);
      ctx.body={
        errcode:0,
        errmsg:'ok',
        list
      };
})


module.exports = router
